<template>
	<el-dialog title="发送消息" v-model="visible" :width="800" :close-on-click-modal="false" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="right">
			<el-form-item label="标题" prop="title">
				<el-input v-model="form.title" placeholder="请输入标题" clearable maxlength="50" show-word-limit></el-input>
			</el-form-item>
			<el-form-item label="接收人" prop="receiverScope">
				<el-select v-model="form.receiverScope" @change="changeSelect" style="width: 100%;" placeholder="请选择接收人" clearable>
					<el-option v-for="(item, index) in flowlist" :key="index" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="用户" prop="receiverScopeParam" v-if="form.receiverScope != 'all'">
				<el-button type="primary" @click="addUserFun" size="small">添加用户</el-button>
				<el-button type="text" v-if="selectedMembers && selectedMembers.length">已添加{{selectedMembers.length}}个用户</el-button>
			</el-form-item>
			<el-form-item label="发送内容" prop="content">
				<sc-editor v-model="form.content" placeholder="请输入" :height="400"></sc-editor>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false" >取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">发送</el-button>
		</template>
	</el-dialog>
	<selectDom 
		ref="selectDom" 
		@submit="submitAdd" 
		v-if="dialog.user" 
		@close="dialog.user = false"
		:apiObj="selectApiObj"
		:treeSearch="{type: '2'}"
		:merberSearch="{id: 'companyId'}"
		:defaultSearch="{status: '1'}"
	></selectDom>
</template>

<script>
	import { defineAsyncComponent } from 'vue'
	const scEditor = defineAsyncComponent(() => import('@/components/scEditor'))
	import selectDom from './components/selectDom'
	export default {
		emits: ['success', 'closed'],
		components: {
			scEditor,
			selectDom
		},
		data() {
			return {
				visible: false,
				isSaveing: false,
				flowlist: [
					{label: "学员", value: 'user'},
					{label: "机构", value: 'agent'},
					{label: "教练", value: 'teacher'}
				],
				selectedMembers: [],
				selectedCompany: [],
				dialog: {
					user: false,
					company: false
				},
				//表单数据
				form: {
					title: "",
					content: "",
					receiverScope: "",
					receiverScopeParam: "",
					pushType: 1
				},
				//验证规则
				rules: {
					title: [
						{required: true, message: '请输入标题'}
					],
					content: [
						{required: true, message: '请输入发送内容'}
					],
					receiverScope: [
						{required: true, message: '请选择接收人', trigger: 'change'}
					],
					receiverScopeParam: [
						{required: false, message: '请选择用户', trigger: 'change'}
					],
				},
				selectApiObj: {}
			}
		},
		mounted() {
			
		},
		watch: {

		},
		methods: {
			// 确认选择
			async submitAdd(data){
				let ids = data.map(item => { return item.id })
				this.dialog.user = false
				this.form.receiverScopeParam = ids
				this.selectedMembers = data
			},
			//切换选择
			async changeSelect(e){
				console.log(e, "切换的选择");
			},
			//显示
			open(){
				this.reset();
				this.visible = true;
				return this
			},
			//重置
			reset(){
				this.form = {
					title: "",
					content: "",
					receiverScope: "",
					receiverScopeParam: [],
					pushType: 1
				}
				this.selectedMembers = []
			},
			addUserFun(){
				if (this.form.receiverScope == 'user') {
					this.selectApiObj = this.$API.user.list
				}else if (this.form.receiverScope == 'agent') {
					this.selectApiObj = this.$API.agent.list
				}else if (this.form.receiverScope == 'teacher') {
					this.selectApiObj = this.$API.teacher.list
				}
				
				this.dialog.user = true
				this.$nextTick(() => {
					let arr = JSON.parse(JSON.stringify(this.selectedMembers))
					this.$refs.selectDom.open(arr || [])
				})
			}, 
			//表单提交方法
            submit() {
                this.$refs.dialogForm.validate(async (valid) => {
                    if (!valid) return false

                    let reuqestData = JSON.parse(JSON.stringify(this.form))
                    if (!reuqestData.receiverScopeParam) {
                        reuqestData.receiverScopeParam = []
                    }

                    try {
                        this.isSaveing = true;
                        await this.$API.message.action.post(reuqestData).then(res => {
                            this.isSaveing = false
                            if (res.error === 0) {
                                this.$emit('success')
                                this.visible = false;
                                this.$message.success("发送成功")
                            }
                        })
                    } catch (error) {
                        this.isSaveing = false;
                    }
                })
            }
		}
	}
</script>

<style scoped>
:deep(.ck.ck-editor__main>.ck-editor__editable) {
    height: 200px !important;
}
</style>
